﻿using HR60_PanelSoft.NetWork.Dto;
using HR60_PanelSoft.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Management;
using System.Threading;
using HR60_PanelSoft.Tools;
using System.IO.Ports;
using System.Windows.Forms;
using HR60_PanelSoft.NetWork.Base;
using System.IO;
using HR60_PanelSoft.NetWork.Sender;
using HR60_PanelSoft.Model.BaseModel;
using HR60_PanelSoft.Service;


namespace HR60_PanelSoft.NetWork
{
    public interface IProcessHandle
    {
        void onError(string errStr);

        void onProcess(int percent);
    }



    public class NetService
    {



        public bool isAdbUse(GateWayDto gateWay)
        {
            bool isUse=false;
            try
            {
                TcpClient tcp = new TcpClient();
                tcp.Connect(IPAddress.Parse(gateWay.Ip), 5037);
                isUse = tcp.Connected;
                tcp.Close();
            }
            catch (Exception e)
            {
                LogUils.error("isAdbUse ", e);
            }
            return isUse;
           
        }


        //扫描设备
        public List<GateWayDto> scanGateWay(string _ip,IProcessHandle handle)
       //       public List<GateWayDto> scanGateWay(IProcessHandle handle)
        {

            LogUils.info("scanGateWay", "扫描开始");
            List<GateWayDto> result = new List<GateWayDto>();

            //  NetUtils.newSendUDPClient("255.255.255.255", Config.BROADCAST_PORT);

            List<string> ipList = NetUtils.getIPAddress();
            List<string> netmaskList = NetUtils.GetNetMask();

            int curr = ipList.IndexOf(_ip);
            if (curr == -1)
            {

                LogUils.error("scanGateWay", "参数错误,ip不存在");
                throw new Exception("参数错误,ip不存在");
            }

            LogUils.info("scanGateWay,broadcastIp:", NetUtils.getBroadcast(ipList[curr], netmaskList[curr]));
            NetUtils.newSendUDPClient(NetUtils.getBroadcast(ipList[curr], netmaskList[curr]), Config.BROADCAST_PORT);

            NetUtils.newRecvUDPClient(Config.BROADCAST_PORT);
            byte[] buf = new byte[32];

            buf[0] = 0xFE;

            buf[1] = 0xFE;

            buf[2] = 32;

            buf[3] = 0x01;

            buf[4] = 0x00;

            buf[5] = 0x00;

            buf[6] = 0x00;

            buf[7] = 0x00;

            buf[8] = 0x00;

            buf[9] = 0xFF;

            string macs = GetMacAddress();

            string ips = _ip;

            string[] mac = macs.Split(':');

            string[] ip = ips.Split('.');

            buf[10] = Convert.ToByte(mac[0], 16);

            buf[11] = Convert.ToByte(mac[1], 16);

            buf[12] = Convert.ToByte(mac[2], 16);

            buf[13] = Convert.ToByte(mac[3], 16);

            buf[14] = Convert.ToByte(mac[4], 16);

            buf[15] = Convert.ToByte(mac[5], 16);

            buf[16] = Convert.ToByte(ip[0], 10);

            buf[17] = Convert.ToByte(ip[1], 10);

            buf[18] = Convert.ToByte(ip[2], 10);

            buf[19] = Convert.ToByte(ip[3], 10);

            buf[30] = 0x00;

            buf[31] = 0xFD;

            object[] param = new object[3];
            param[0] = result;
            param[1] = handle;
            param[2] = _ip;

            Thread t = new Thread(new ParameterizedThreadStart(RecvThread));

            t.IsBackground = true;

            t.Start(param);

            Thread.Sleep(1000);

            NetUtils.sendDataByUDP(buf);

            //t.Join(6000);

            //等待10s
            for (int i = 1; i <= 100; i++)
            {
                Thread.Sleep(100);
                handle.onProcess(i);

            }

            NetUtils.releaseSendUDPClient();
            NetUtils.releaseRecvUDPClient();

            LogUils.info("scanGateWay", "扫描结束");

            //add temp
            //{
            //    GateWayDto gwd = new GateWayDto();
            //    gwd.DuanYuanNo = "8";
            //    gwd.MenPaiNo = "27";
            //    gwd.NetNo = "33";
            //    gwd.PanelNo = "1";
            //    gwd.SubNo = "1";
            //    gwd.Ip = "192.168.1.10";
            //    gwd.MAC = "111111111111";
            //    result.Add(gwd);
            //}
            //
            return result;
        }

      

        public void RecvThread(object p)
        {


            object param = ((object[])p)[0];
            IProcessHandle  handle = (IProcessHandle)(((object[])p)[1]);

            string ip  =(string)(((object[])p)[2]);
            List<GateWayDto> result = (List<GateWayDto>)param;

           
          
           
            while (true)
            {

              
                try
                {

                    byte[] buf = NetUtils.recvUDPData();
                    IPAddress ipaddr = NetUtils._recvEndpoint.Address;
                    LogUils.info("scanGateWay,recvIp:", ipaddr.ToString());

                  
                    if(NetUtils.getIPAddress().IndexOf(ipaddr.ToString())>= 0)
                        continue;


                    if (buf[0] != 0xFE && buf[1] != 0xFE && buf[3] != 0x01 && buf[2] != 0x20)
                    {
                        Console.WriteLine("package 格式错误！！");
                        continue;
                    }


                    if (buf.Length == 32)
                    {

                        string ver = System.Text.Encoding.Default.GetString(buf, 20, 10);
                        GateWayDto gwd = new GateWayDto();
                        gwd.DuanYuanNo = buf[4].ToString();
                        gwd.MenPaiNo = (buf[5] + (buf[6] << 8)).ToString();
                        gwd.NetNo = buf[7].ToString();
                        gwd.PanelNo = buf[8].ToString();
                        gwd.SubNo = buf[9].ToString();
                        byte[] _mac = new byte[6];
                        Array.Copy(buf, 10, _mac, 0, 6);
                        gwd.MAC = ByteUils.byte2HexString(_mac);
                        gwd.Ip = String.Format("{0:D}.{1:D}.{2:D}.{3:D}", buf[16], buf[17], buf[18], buf[19]); ;
                        gwd.Ver = ver;
                        //ip去掉
                        if (NetUtils.getIPAddress().IndexOf(gwd.Ip) >= 0)
                             continue;

                        result.Add(gwd);
                    }
                }

                catch (Exception e)
                {
                    LogUils.error("RecvThread", e);
                    break;

                }

            }

           



        }


        public void publishSettingFile(GateWayDto gateWay, string path)
        {

            ADBUils uils = new ADBUils();
            try
            {
                uils.AdbPath = Config.adbPath;
                uils.AdbTimeout = Config.adbTimeout;
                uils.Disconnect(gateWay.Ip);
                uils.KillServer();
                uils.StartServer();
                uils.Connect(gateWay.Ip);

               
                uils.Devices();
                if (uils.Output.IndexOf(gateWay.Ip + ":5555") == -1)
                {
                    throw new Exception("设备不在线，请检查设备！！！");

                }
                uils.Push(path, Config.pushSettingFile);
                if (uils.Output.IndexOf("B/s") == -1)
                {
                    throw new Exception("发送配置文件失败！！！");

                }
                LogUils.info("publishSettingFile", "发送配置文件成功！！！");
            }catch(Exception e){
                LogUils.error("publishSettingFile", e);
                throw e;
            }
            finally
            {
                uils.Disconnect(gateWay.Ip);
                uils.KillServer();
            }
           

          
           


        }





        //生成配置文件
     public   void createSettingFile(bool oldVer, GateWayDto gateWay, Net net, ref MemoryStream ms)
        {
            StreamWriter writer = new StreamWriter(ms);
            BaseSender bs = null;
            try
            {


                //1.生成第一行数据 
                writer.WriteLine(gateWay.DuanYuanNo + " " + gateWay.MenPaiNo + " " + gateWay.NetNo + " " + gateWay.PanelNo);
                //2.发送起始报文
                bs = new Sender_0A00();
                StringUils.writeStreamString(writer, bs.getSettingString());
                //3.擦除
                bs = new Sender_0200();
                StringUils.writeStreamString(writer,bs.getSettingString());

                //4.各场景控制灯光控制器参数（Data Type：0x16）
                {
                    List<Scene> scenes = Proj.currentProj.scenes;
                    for (int i = 0; i < scenes.Count; i++)
                    {
                        bs = new Sender_0116((byte)(i + 1), scenes[i]);
                        StringUils.writeStreamString(writer,bs.getSettingString());
                    }
                }

                //5-6-7-8设置场景内容-空调（Data Type：0x00,0x01,0x02,0x03）
                List<DeviceGroup> dgList = Proj.currentProj.deviceGroups;
                Device air = null;
                Device heat = null;
                Device wind = null;
                Device bgm = null;
                foreach (DeviceGroup dg in dgList)
                {

                    List<Device> list = dg.devices;
                    foreach (Device device in list)
                    {
                        if (ExDeviceType.CentralAircon == device.type.exType)
                        {
                            air = device;
                        }
                        else if (ExDeviceType.CentralHeating == device.type.exType)
                        {
                            heat = device;
                        }
                        else if (ExDeviceType.CentralNewWind == device.type.exType)
                        {
                            wind = device;
                        }
                        else if (ExDeviceType.BGM == device.type.exType)
                        {
                            bgm = device;
                        }

                    }

                }

                {
                    if (air != null)
                    {
                        List<Scene> scenes = Proj.currentProj.scenes;

                        for (int i = 0; i < scenes.Count; i++)
                        {
                            bs = new Sender_0100(0x00, ((byte)(i + 1)), scenes[i], air);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }
                    }


                    if (wind != null)
                    {
                        List<Scene> scenes = Proj.currentProj.scenes;

                        for (int i = 0; i < scenes.Count; i++)
                        {
                            bs = new Sender_0101(0x00, ((byte)(i + 1)), scenes[i], wind);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }

                    }


                    if (heat != null)
                    {
                        List<Scene> scenes = Proj.currentProj.scenes;

                        for (int i = 0; i < scenes.Count; i++)
                        {
                            bs = new Sender_0102(0x00, ((byte)(i + 1)), scenes[i], heat);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }

                    }


                    if (bgm != null)
                    {
                        List<Scene> scenes = Proj.currentProj.scenes;

                        for (int i = 0; i < scenes.Count; i++)
                        {
                            bs = new Sender_0103(0x00, ((byte)(i + 1)), scenes[i], bgm);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }

                    }

                }

                //9,10,11,12设置空调名称（Data Type：0x04）

                {

                    List<DeviceGroup> deviceGroups = Proj.currentProj.deviceGroups;

                    foreach (DeviceGroup dg in deviceGroups)
                    {
                        List<Device> devices = dg.devices;

                        foreach (Device device in devices)
                        {
                            List<Device> childDevices = device.childDevices;
                            int i = 0;
                            foreach (Device childDevice in childDevices)
                            {
                                i++;
                                if (ExDeviceType.CentralAircon == device.type.exType)
                                {
                                    bs = new Sender_0104(0x00, (byte)i, childDevice, device);
                                }
                                else if (ExDeviceType.CentralHeating == device.type.exType)
                                {
                                    bs = new Sender_0105(0x00, (byte)i, childDevice, device);
                                }
                                else if (ExDeviceType.CentralNewWind == device.type.exType)
                                {
                                    bs = new Sender_0106(0x00, (byte)i, childDevice, device);
                                }
                                else if (ExDeviceType.BGM == device.type.exType)
                                {
                                    bs = new Sender_0107(0x00, (byte)i, childDevice, device);
                                }

                                StringUils.writeStreamString(writer,bs.getSettingString());
                            }
                        }
                    }
                }


                //13主菜单（Data Type：0x08）
                {
                    List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                    foreach (HR60_PanelSoft.Model.Panel p in panels)
                    {
                        bs = new Sender_0108((byte)(p.index), p);
                        StringUils.writeStreamString(writer,bs.getSettingString());


                        bs = new Sender_0109((byte)(p.index), p);
                        StringUils.writeStreamString(writer,bs.getSettingString());


                        bs = new Sender_010A((byte)(p.index), p);
                        StringUils.writeStreamString(writer,bs.getSettingString());

                        bs = new Sender_010B((byte)(p.index), p);
                        StringUils.writeStreamString(writer,bs.getSettingString());


                        bs = new Sender_010C((byte)(p.index), p);
                        StringUils.writeStreamString(writer,bs.getSettingString());

                    }

                }


                //14

                {

                    bool isAir = false;
                    bool isAir485 = false;
                    byte airSum = 0x00;
                    byte airBrand = 0x00;
                    bool isHeat = false;
                    bool isHeat485 = false;
                    byte heatSum = 0x00;
                    byte heatBrand = 0x00;
                    bool isWind = false;
                    bool isWind485 = false;
                    byte windSum = 0x00;
                    byte windBrand = 0x00;
                    bool isBJY = false;
                    byte bjySum = 0x00;
                    byte bjyBrand = 0x00;

                    //查找高级设备信息 
                    List<DeviceGroup> deviceGroups = Proj.currentProj.deviceGroups;

                    foreach (DeviceGroup dg in deviceGroups)
                    {
                        List<Device> devices = dg.devices;

                        foreach (Device device in devices)
                        {
                            List<Device> childDevices = device.childDevices;

                            foreach (Device childDevice in childDevices)
                            {

                                if (ExDeviceType.CentralAircon == device.type.exType)
                                {
                                    isAir = true;
                                    if (device.type.name == "中央空调系统-485型")
                                    {
                                        isAir485 = true;
                                    }

                                    airSum = (byte)childDevices.Count;

                                    airBrand = Convert.ToByte(device.brand.protocolTag);

                                }
                                else if (ExDeviceType.CentralHeating == device.type.exType)
                                {
                                    isHeat = true;
                                    if (device.type.name == "中央供暖系统-485型")
                                    {
                                        isHeat485 = true;
                                    }
                                    heatSum = (byte)childDevices.Count;
                                    heatBrand = Convert.ToByte(device.brand.protocolTag);


                                }
                                else if (ExDeviceType.CentralNewWind == device.type.exType)
                                {
                                    isWind = true;
                                    if (device.type.name == "新风系统-485型")
                                    {
                                        isWind485 = true;
                                    }
                                    windSum = (byte)childDevices.Count;
                                    windBrand = Convert.ToByte(device.brand.protocolTag);

                                }
                                else if (ExDeviceType.BGM == device.type.exType)
                                {
                                    isBJY = true;
                                    bjySum = (byte)childDevices.Count;
                                    bjyBrand = Convert.ToByte(device.brand.protocolTag);

                                }

                            }
                        }
                    }





                    List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                    foreach (HR60_PanelSoft.Model.Panel p in panels)
                    {
                        bs = new Sender_010D((byte)(p.index), p, isAir, isAir485, airSum, airBrand, isHeat, isHeat485, heatSum, heatBrand
                         , isWind, isWind485, windSum, windBrand
                         , isBJY, bjySum, bjyBrand);
                        StringUils.writeStreamString(writer,bs.getSettingString());
                    }

                }


                //15.

                {

                    List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                    foreach (HR60_PanelSoft.Model.Panel p in panels)
                    {

                        bs = new Sender_010F((byte)(p.index), p);
                        StringUils.writeStreamString(writer,bs.getSettingString());

                        bs = new Sender_0110((byte)(p.index), p);
                        StringUils.writeStreamString(writer,bs.getSettingString());




                        List<LoadPin> loadPins = p.loadPins;
                        foreach (LoadPin lp in loadPins)
                        {
                            bs = new Sender_010E((byte)(p.index), p, lp);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }


                        List<PanelPage> pages = p.pages;
                        int j = 0;
                        for (int i = 0; i < pages.Count; i++)
                        {
                            PanelPage pp = pages[i];
                            List<PanelButton> buttons = pp.buttons;
                          
                            foreach (PanelButton pb in buttons)
                            {

                                Device d = pb.getMappingDevice();
                                Scene s = pb.getMappingScene();
                                if (d != null || s != null)
                                {
                                    bs = new Sender_0111((byte)(p.index), p, j + 1, pb);
                                    StringUils.writeStreamString(writer, bs.getSettingString());
                                    j++;
                                }

                               
                            }
                        }

                        //场景
                        List<PanelPage> sencePages = p.pages;
                        j = 0;
                        for (int i = 0; i < sencePages.Count; i++)
                        {
                            PanelPage pp = sencePages[i];
                            List<PanelButton> buttons = pp.buttons;
                            foreach (PanelButton pb in buttons)
                            {
                                Scene s = pb.getMappingScene();
                                if (s != null)
                                {
                                    bs = new Sender_0112((byte)(p.index), p, j + 1, pb);
                                    StringUils.writeStreamString(writer, bs.getSettingString());
                                    j++;
                                }
                               

                            }
                        }
                    }
                }


                //16
                {
                    List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                    foreach (HR60_PanelSoft.Model.Panel p in panels)
                    {
                        List<Scene> scenes = Proj.currentProj.scenes;
                        foreach (Scene s in scenes)
                        {

                            bs = new Sender_0113((byte)(p.index), p, s);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }
                    }
                }

                //17
                {

                    List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                    foreach (HR60_PanelSoft.Model.Panel p in panels)
                    {
                        bs = new Sender_0114((byte)(p.index), p);
                        StringUils.writeStreamString(writer,bs.getSettingString());

                    }

                }

                //18
                {

                    List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                    foreach (HR60_PanelSoft.Model.Panel p in panels)
                    {
                        if (p.airconPage != null)
                        {
                            bs = new Sender_0115((byte)(p.index), 1, p.airconPage);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }

                        if (p.heatingPage != null)
                        {
                            bs = new Sender_0115((byte)(p.index ), 2, p.heatingPage);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }

                        if (p.newWindPage != null)
                        {
                            bs = new Sender_0115((byte)(p.index), 3, p.newWindPage);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }

                        if (p.bgmPage != null)
                        {
                            bs = new Sender_0115((byte)(p.index), 4, p.bgmPage);
                            StringUils.writeStreamString(writer,bs.getSettingString());
                        }

                    }
                }

                //19

                bs = new Sender_0B00();
                StringUils.writeStreamString(writer,bs.getSettingString());


                writer.Flush();
                LogUils.info("createSettingFile", "成功!!");
            }
            catch(Exception e)
            {
                LogUils.error("createSettingFile", e);
                throw e;
            }

        }

        //发布网关
    public    void publishByGateWay(bool oldVer, GateWayDto gateWay, Net net, IProcessHandle handle)
        {

          
          try
            {
                Config.sendType = 1;
                NetUtils.newSendUDPClient(gateWay.Ip, Config.RECV_PORT);
                
                innerPublish(net, handle);
              
                LogUils.info("publishByGateWay", "发送成功!!");
            }
            catch(Exception e)
            {
                LogUils.error("publishByGateWay", e);
                throw e;
            }
          finally
          {
              NetUtils.releaseSendUDPClient();
            
          }


        }




        //发布60
     public   void publishByCom(bool oldVer, string comName, Net net, IProcessHandle handle)
        {
            try
            {
                Config.sendType = 0;
                NetUtils.startSerial(comName);

                innerPublish(net, handle);
                LogUils.info("publishByGateWay", "发送成功!!");
            }catch(Exception e){
                LogUils.error("publishByCom", e);
                throw e;
            }
            finally
            {
                NetUtils.releaseSerial(comName);
            }
          
          
           

        }


        //设置网关
    public    void setGateWay(GateWayDto gateWay)
        {
            Config.sendType = 1;
            NetUtils.newSendUDPClient(gateWay.Ip, Config.RECV_PORT);
          
            try
            {

                byte[] buf = new byte[32];
                {
                    buf[0] = 0xFE;
                    buf[1] = 0xFE;
                    buf[2] = 0x16;
                    buf[3] = 0x04;  //类型
                    buf[4] = Convert.ToByte(gateWay.DuanYuanNo);
                    buf[5] = (byte)((Convert.ToInt16(gateWay.MenPaiNo) >> 8) & 0xFF);
                    buf[6] = (byte)((Convert.ToInt16(gateWay.MenPaiNo)) & 0xFF);
                    buf[7] = Convert.ToByte(gateWay.NetNo);
                    buf[8] = Convert.ToByte(gateWay.PanelNo);
                    buf[9] = Convert.ToByte(gateWay.SubNo);
                    byte[] mac = ByteUils.string2hex(gateWay.MAC);
                    byte[] ip = ByteUils.ip2hex(gateWay.Ip);
                    buf[10] = mac[0];
                    buf[11] = mac[1];
                    buf[12] = mac[2];
                    buf[13] = mac[3];
                    buf[14] = mac[4];
                    buf[15] = mac[5];
                    buf[16] = ip[0];
                    buf[17] = ip[1];
                    buf[18] = ip[2];
                    buf[19] = ip[3];
                    buf[30] = 0x00;
                    buf[31] = 0xFD;
                }
                NetUtils.sendDataByUDP(buf);
                Byte[] data = NetUtils.recvSendClientUDPData();


                if (data == null || data.Length != 32)
                {
                    throw new Exception("长度不对!!");
                   
                }

                if (data[0] != 0xFE && data[1] != 0xFE && data[2] != 0x20 && data[3] != 0x05 && data[30] != 0x01)
                {

                    throw new Exception("接收失败!!");
                   
                }

                LogUils.info("setGateWay", "setGateWay成功!!");

               
            }
            catch (Exception e)
            {
              
                LogUils.error("setGateWay", e);
                throw new Exception(e.Message);
            }
            finally
            {
                NetUtils.releaseSendUDPClient();
            
              
            }

        }


        //通过串口设置设备
      public  void setDeviceByCom(int unitSn, int roomSn, int netId, int panelId, string comName)
        {
            Config.sendType = 0;
            NetUtils.startSerial(comName);
       
            try
            {
                new Sender_1000((byte)netId, (byte)(panelId), (byte)unitSn, (byte)roomSn).send();
                LogUils.info("setDeviceByGateWay", "发送成功!!");
            }
            catch (Exception e)
            {
             
                LogUils.error("setDeviceByGateWay", e);
                throw new Exception(e.Message);

            }
            finally
            {
                NetUtils.releaseSerial(comName);
              
            }

             


        }

        //通过网关设置设备
     public   void setDeviceByGateWay(int unitSn, int roomSn, int netId, int panelId, GateWayDto gateWay)
        {
            Config.sendType = 1;
            NetUtils.newSendUDPClient(gateWay.Ip, Config.RECV_PORT);
          
            try {
                new Sender_1000((byte)netId, (byte)(panelId), (byte)unitSn, (byte)roomSn).send();
                LogUils.info("setDeviceByGateWay", "发送成功!!");
            }
            catch (Exception e)
            {
                LogUils.error("setDeviceByGateWay",e);
                throw new Exception(e.Message);
            }
            finally
            {
                NetUtils.releaseSendUDPClient();
             
            }
            
        }

        //升级网关
    public    void updateGateWay(GateWayDto gateWay, string path, IProcessHandle handle)
        {

            if (path.IndexOf(".zip") == -1)
            {

                throw new Exception("文件有问题,请确保文件是否正确?");
              
            }

            ADBUils uils = new ADBUils();
            try
            {
                uils.AdbPath = Config.adbPath;
                uils.AdbTimeout = Config.adbTimeout;
                uils.Disconnect(gateWay.Ip);
                uils.KillServer();
                uils.StartServer();
                uils.Connect(gateWay.Ip);
                handle.onProcess(10);
                uils.Devices();
                if (uils.Output.IndexOf(gateWay.Ip + ":5555") == -1)
                {
                    throw new Exception("设备不在线，请检查设备！！！");


                }
                handle.onProcess(20);
                uils.Execute("rm -rf /data/misc/smarthome/update/temp");

                uils.Execute("mkdir /data/misc/smarthome/update/temp");

                uils.Execute("ls /data/misc/smarthome/update/temp");

                if (uils.Output.IndexOf("No such file") > 0)
                {
                    throw new Exception("升级文件失败，请重试！！！");

                }





                string temp = System.Environment.GetEnvironmentVariable("TEMP");
                temp = temp + "/hr60";
                DirectoryInfo info = new DirectoryInfo(temp);
                if (!info.Exists)
                {

                    try
                    {
                        info.Create();
                    }
                    catch (Exception e)
                    {
                        LogUils.error("updateGateWay", e);
                        throw new Exception("创建解压临时目录失败,请确保权限问题！");


                    }

                }
                else
                {
                    try
                    {
                        info.Delete(true);
                        info.Create();
                    }
                    catch (Exception e)
                    {
                        LogUils.error("updateGateWay", e);
                        throw new Exception("创建删除或创建临时目录失败,请确保权限问题！");


                    }
                }

                if (!ZipUils.UnZip(path, temp))
                {

                    LogUils.error("updateGateWay", "解压失败");
                    throw new Exception("解压临时目录失败,请确保权限问题！");

                }

                FileInfo[] tempFileList = info.GetFiles();
                if (tempFileList.Length == 0)
                {
                    if(info.GetDirectories().Length ==0)
                        throw new Exception("升级失败,请确保升级文件是否有问题！");

                    tempFileList = info.GetDirectories()[0].GetFiles();
                }
                foreach (FileInfo fi in tempFileList)
                {
                    uils.Push(fi.FullName, Config.pushUpdateSoftPath);
                }
                LogUils.info("updateGateWay", "升级成功！");
            }catch(Exception e){
                LogUils.error("updateGateWay", e);
                throw e;
            }
            finally
            {
                uils.Disconnect(gateWay.Ip);
                uils.KillServer();

            }
           
        }


        void innerPublish(Net net, IProcessHandle handle)
        {


            int progress = 0;
            handle.onProcess(1);
            BaseSender bs = null;

            //1.发送起始报文
            bs = new Sender_0A00();
            bs.send();
            handle.onProcess(2);
            //3.擦除
            bs = new Sender_0200();
            bs.send();
            handle.onProcess(3);

            //4.各场景控制灯光控制器参数（Data Type：0x16）
            {
                List<Scene> scenes = Proj.currentProj.scenes;
                for (int i = 0; i < scenes.Count; i++)
                {
                    bs = new Sender_0116((byte)(i + 1), scenes[i]);
                    bs.send();
                   
                }
            }
            handle.onProcess(10);
            //5-6-7-8设置场景内容-空调（Data Type：0x00,0x01,0x02,0x03）
            List<DeviceGroup> dgList = Proj.currentProj.deviceGroups;
            Device air = null;
            Device heat = null;
            Device wind = null;
            Device bgm = null;
            foreach (DeviceGroup dg in dgList)
            {

                List<Device> list = dg.devices;
                foreach (Device device in list)
                {
                    if (ExDeviceType.CentralAircon == device.type.exType)
                    {
                        air = device;
                    }
                    else if (ExDeviceType.CentralHeating == device.type.exType)
                    {
                        heat = device;
                    }
                    else if (ExDeviceType.CentralNewWind == device.type.exType)
                    {
                        wind = device;
                    }
                    else if (ExDeviceType.BGM == device.type.exType)
                    {
                        bgm = device;
                    }

                }

            }

            {
                if (air != null)
                {
                    List<Scene> scenes = Proj.currentProj.scenes;

                    for (int i = 0; i < scenes.Count; i++)
                    {
                        bs = new Sender_0100(0x00, ((byte)(i + 1)), scenes[i], air);
                        bs.send();
                      
                    }
                }


                if (wind != null)
                {
                    List<Scene> scenes = Proj.currentProj.scenes;

                    for (int i = 0; i < scenes.Count; i++)
                    {
                        bs = new Sender_0101(0x00, ((byte)(i + 1)), scenes[i], wind);
                        bs.send();
                        handle.onProcess(progress++);
                    }

                }


                if (heat != null)
                {
                    List<Scene> scenes = Proj.currentProj.scenes;

                    for (int i = 0; i < scenes.Count; i++)
                    {
                        bs = new Sender_0102(0x00, ((byte)(i + 1)), scenes[i], heat);
                        bs.send();
                        handle.onProcess(progress++);
                    }

                }


                if (bgm != null)
                {
                    List<Scene> scenes = Proj.currentProj.scenes;

                    for (int i = 0; i < scenes.Count; i++)
                    {
                        bs = new Sender_0103(0x00, ((byte)(i + 1)), scenes[i], bgm);
                        bs.send();
                        handle.onProcess(progress++);
                    }

                }

            }
            handle.onProcess(20);
            //9,10,11,12设置空调名称（Data Type：0x04）

            {

                List<DeviceGroup> deviceGroups = Proj.currentProj.deviceGroups;

                foreach (DeviceGroup dg in deviceGroups)
                {
                    List<Device> devices = dg.devices;

                    foreach (Device device in devices)
                    {
                        List<Device> childDevices = device.childDevices;
                        int i = 0;
                        foreach (Device childDevice in childDevices)
                        {
                            i++;
                            if (ExDeviceType.CentralAircon == device.type.exType)
                            {
                                bs = new Sender_0104(0x00, (byte)i, childDevice, device);
                            }
                            else if (ExDeviceType.CentralHeating == device.type.exType)
                            {
                                bs = new Sender_0105(0x00, (byte)i, childDevice, device);
                            }
                            else if (ExDeviceType.CentralNewWind == device.type.exType)
                            {
                                bs = new Sender_0106(0x00, (byte)i, childDevice, device);
                            }
                            else if (ExDeviceType.BGM == device.type.exType)
                            {
                                bs = new Sender_0107(0x00, (byte)i, childDevice, device);
                            }

                            bs.send();
                          
                        }
                    }
                }
            }
            handle.onProcess(30);

            //13主菜单（Data Type：0x08）
            {
                List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                foreach (HR60_PanelSoft.Model.Panel p in panels)
                {
                    bs = new Sender_0108((byte)(p.index), p);
                    bs.send();


                    bs = new Sender_0109((byte)(p.index), p);
                    bs.send();


                    bs = new Sender_010A((byte)(p.index), p);
                    bs.send();

                    bs = new Sender_010B((byte)(p.index), p);
                    bs.send();


                    bs = new Sender_010C((byte)(p.index), p);
                    bs.send();

                }

            }
            handle.onProcess(50);

            //14

            {

                bool isAir = false;
                bool isAir485 = false;
                byte airSum = 0x00;
                byte airBrand = 0x00;
                bool isHeat = false;
                bool isHeat485 = false;
                byte heatSum = 0x00;
                byte heatBrand = 0x00;
                bool isWind = false;
                bool isWind485 = false;
                byte windSum = 0x00;
                byte windBrand = 0x00;
                bool isBJY = false;
                byte bjySum = 0x00;
                byte bjyBrand = 0x00;

                //查找高级设备信息 
                List<DeviceGroup> deviceGroups = Proj.currentProj.deviceGroups;

                foreach (DeviceGroup dg in deviceGroups)
                {
                    List<Device> devices = dg.devices;

                    foreach (Device device in devices)
                    {
                        List<Device> childDevices = device.childDevices;

                        foreach (Device childDevice in childDevices)
                        {

                            if (ExDeviceType.CentralAircon == device.type.exType)
                            {
                                isAir = true;
                                if (device.type.name == "中央空调系统-485型")
                                {
                                    isAir485 = true;
                                }

                                airSum = (byte)childDevices.Count;

                                airBrand = Convert.ToByte(device.brand.protocolTag);

                            }
                            else if (ExDeviceType.CentralHeating == device.type.exType)
                            {
                                isHeat = true;
                                if (device.type.name == "中央供暖系统-485型")
                                {
                                    isHeat485 = true;
                                }
                                heatSum = (byte)childDevices.Count;
                                heatBrand = Convert.ToByte(device.brand.protocolTag);


                            }
                            else if (ExDeviceType.CentralNewWind == device.type.exType)
                            {
                                isWind = true;
                                if (device.type.name == "新风系统-485型")
                                {
                                    isWind485 = true;
                                }
                                windSum = (byte)childDevices.Count;
                                windBrand = Convert.ToByte(device.brand.protocolTag);

                            }
                            else if (ExDeviceType.BGM == device.type.exType)
                            {
                                isBJY = true;
                                bjySum = (byte)childDevices.Count;
                                bjyBrand = Convert.ToByte(device.brand.protocolTag);

                            }

                        }
                    }
                }



                handle.onProcess(60);

                List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                foreach (HR60_PanelSoft.Model.Panel p in panels)
                {
                    bs = new Sender_010D((byte)(p.index), p, isAir, isAir485, airSum, airBrand, isHeat, isHeat485, heatSum, heatBrand
                     , isWind, isWind485, windSum, windBrand
                     , isBJY, bjySum, bjyBrand);
                    bs.send();
                  
                }

            }

            handle.onProcess(65);
            //15.

            {

                List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                foreach (HR60_PanelSoft.Model.Panel p in panels)
                {

                    bs = new Sender_010F((byte)(p.index), p);
                    bs.send();

                    bs = new Sender_0110((byte)(p.index), p);
                    bs.send();

                 


                    List<LoadPin> loadPins = p.loadPins;
                    foreach (LoadPin lp in loadPins)
                    {
                        bs = new Sender_010E((byte)(p.index), p, lp);
                        bs.send();
                    }


                    List<PanelPage> pages = p.pages;
                    int j = 0;
                    for (int i = 0; i < pages.Count; i++)
                    {
                        PanelPage pp = pages[i];
                        List<PanelButton> buttons = pp.buttons;
                        
                        foreach (PanelButton pb in buttons)
                        {

                              Device d = pb.getMappingDevice();
                              Scene s = pb.getMappingScene();
                              if (d != null || s != null)
                              {
                                    bs = new Sender_0111((byte)(p.index), p, j + 1, pb);
                                    bs.send();
                                    j++;
                              }
                        }
                    }

                    //场景
                    List<PanelPage> sencePages = p.scenePages;
                    j = 0;
                    for (int i = 0; i < sencePages.Count; i++)
                    {
                        PanelPage pp = sencePages[i];
                        List<PanelButton> buttons = pp.buttons;
                        foreach (PanelButton pb in buttons)
                        {
                            Scene s = pb.getMappingScene();
                            if (s != null)
                            {
                                bs = new Sender_0112((byte)(p.index), p, j + 1, pb);
                                bs.send();
                             
                                j++;
                            }
                           
                        }
                    }
                }
            }

            handle.onProcess(85);
            //16
            {
                List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                foreach (HR60_PanelSoft.Model.Panel p in panels)
                {
                    List<Scene> scenes = Proj.currentProj.scenes;
                    foreach (Scene s in scenes)
                    {

                        bs = new Sender_0113((byte)(p.index), p, s);
                        bs.send();
                       
                    }
                }
            }
           
            //17
            {

                List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                foreach (HR60_PanelSoft.Model.Panel p in panels)
                {
                    bs = new Sender_0114((byte)(p.index), p);
                    bs.send();

                }

            }
            handle.onProcess(90);
            //18
            {

                List<HR60_PanelSoft.Model.Panel> panels = net.panels;

                foreach (HR60_PanelSoft.Model.Panel p in panels)
                {
                    if (p.airconPage != null)
                    {
                        bs = new Sender_0115((byte)(p.index), 1, p.airconPage);
                        bs.send();
                    }

                    if (p.heatingPage != null)
                    {
                        bs = new Sender_0115((byte)(p.index), 2, p.heatingPage);
                        bs.send();
                    }

                    if (p.newWindPage != null)
                    {
                        bs = new Sender_0115((byte)(p.index), 3, p.newWindPage);
                        bs.send();
                    }

                    if (p.bgmPage != null)
                    {
                        bs = new Sender_0115((byte)(p.index), 4, p.bgmPage);
                        bs.send();
                    }

                }
            }
            //o
            bs = new Sender_0B00();
            bs.send();

            handle.onProcess(100);
        }


        private static string GetIPAddress()
        {

            try
            {

                //获取IP地址 

                string st = "";

                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject mo in moc)
                {

                    if ((bool)mo["IPEnabled"] == true)
                    {

                        //st=mo["IpAddress"].ToString(); 

                        System.Array ar;

                        ar = (System.Array)(mo.Properties["IpAddress"].Value);

                        st = ar.GetValue(0).ToString();

                        break;

                    }

                }

                moc = null;

                mc = null;

                return st;

            }

            catch
            {

                return "unknow";

            }

            finally
            {

            }



        }



        private static string GetMacAddress()
        {

            try
            {

                //获取网卡硬件地址 

                string mac = "";

                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject mo in moc)
                {

                    if ((bool)mo["IPEnabled"] == true)
                    {

                        mac = mo["MacAddress"].ToString();

                        break;

                    }

                }

                moc = null;

                mc = null;

                return mac;

            }

            catch
            {

                return "unknow";

            }

            finally
            {

            }



        }










    }
}
